package setting

import (
	"fmt"
	"log"
	"time"

	"github.com/go-ini/ini"
)

var (
	Run_Mode   string
	Page_Size  int
	Jwt_Secret string

	Http_Port     int
	Read_Timeout  time.Duration
	Write_Timeout time.Duration

	SqlType      string
	Dns          string
	Table_Prefix string
)

var cfg *ini.File

func init() {
	var err error
	cfgFilePath := "conf/app.ini"
	cfg, err = ini.Load(cfgFilePath)

	if err != nil {
		log.Fatalf("加载配置文件【%s】失败，err=%v", cfgFilePath, err)
	}

	loadBase()
	loadApp()
	loadServer()
	loadDatabase()
}

func loadBase() {
	Run_Mode = cfg.Section("").Key("Run_Mode").MustString("Debug")
}

func loadApp() {
	app, err := cfg.GetSection("App")
	if err != nil {
		log.Fatalln("加载app配置节点失败")
	}

	Page_Size = app.Key("Page_Size").MustInt(10)
	Jwt_Secret = app.Key("Jwt_Secret").MustString("1234567890")
}

func loadServer() {
	app, err := cfg.GetSection("Server")
	if err != nil {
		log.Fatalln("加载Server配置节点失败")
	}

	Http_Port = app.Key("Http_Port").MustInt(8080)
	Read_Timeout = time.Duration(app.Key("Read_Timeout").MustInt(60))
	Write_Timeout = time.Duration(app.Key("Write_Timeout").MustInt(60))
}

func loadDatabase() {
	app, err := cfg.GetSection("Database")
	if err != nil {
		log.Fatalln("加载Database配置节点失败")
	}

	SqlType = app.Key("Mysql").MustString("mysql")
	Table_Prefix = app.Key("Table_Prefix").MustString("Blog_")

	user := app.Key("User").MustString("sa")
	pwd := app.Key("Password").MustString("123456")
	host := app.Key("Host").MustString("localhost:3306")
	name := app.Key("Name").MustString("Blog")
	Dns = fmt.Sprintf("%s：%s@tcp(%s)/%s", user, pwd, host, name)
}
